package online.westonline.com.westonline.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.internal.BottomNavigationItemView;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.easy.west.westclient.api.login.bean.User;
import com.easy.west.westclient.api.message.bean.MessageBean;
import com.easy.west.westclient.api.message.event.FindAllMessage2Event;
import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;
import com.jaeger.library.StatusBarUtil;
import com.wingsofts.byeburgernavigationview.ByeBurgerBehavior;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.nekocode.badge.BadgeDrawable;
import online.westonline.com.westonline.MyApplication;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.adapter.HomeViewPagerAdapter;
import online.westonline.com.westonline.base.BaseActivity;
import online.westonline.com.westonline.event.PushNotifyEvent;
import online.westonline.com.westonline.ui.fragment.ConstactFragment;
import online.westonline.com.westonline.ui.fragment.MeetingFragment;
import online.westonline.com.westonline.ui.fragment.MessageFragment;
import online.westonline.com.westonline.ui.fragment.NewsFragment;
import online.westonline.com.westonline.ui.fragment.WorkFragment;
import online.westonline.com.westonline.utils.CacheUtils;
import online.westonline.com.westonline.utils.UiUtlis;

/***
 * 首页
 * 1.极光登录(搬过来)
 * 2.获取消息列表数据
 */
public class HomeActivity extends BaseActivity {


    @BindView(R.id.tv_home_title)
    TextView tvHomeTitle;
    @BindView(R.id.tool_home_bar)
    Toolbar toolHomeBar;
    @BindView(R.id.view_home_pager)
    ViewPager viewHomePager;
    @BindView(R.id.bottom_home_bar)
    BottomNavigationViewEx bottomHomeBar;
    /*
    @BindView(R.id.left_menu)
    NavigationView leftMenu;
    */
    @BindView(R.id.dra_home_layout)
    DrawerLayout draHomeLayout;
    /*
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    */
    @BindView(R.id.coordinator_layout)
    CoordinatorLayout coordinatorLayout;
    @BindView(R.id.app_bar_lay)
    AppBarLayout appBarLay;
    private TextView tv_left_name;
    private TextView tv_left_avator;
    private View headerview;
    private User user;
    private List<Fragment> fragments = new ArrayList<>();
    private MessageFragment messageFragment;
    private WorkFragment workFragment;
    private MeetingFragment meetingFragment;
    private NewsFragment newsFragment;
    private ConstactFragment constactFragment;
    //适配
    private HomeViewPagerAdapter viewPagerAdapter;
    private List<MessageBean> messageBeanList = new ArrayList<>();
    private View message_tab_view;
    private View bage_view;
    private ImageView img_notice_bage_view;
    private int count;

    @Override
    protected void initview() {
        initui();
        //initleftmenu();
        initsession();

    }

    /**
     * 事件初始化
     */
    private void initsession() {
        //点击打开侧滑
        /*
        tvUserName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleDrawer();
            }
        });
        */
        //底部选中监听事件
        bottomHomeBar.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_message:
                        tvHomeTitle.setText("会话");
                        toolHomeBar.setVisibility(View.VISIBLE);
                        ByeBurgerBehavior.from(bottomHomeBar).show();
                        break;
                    case R.id.action_work:
                        toolHomeBar.setVisibility(View.VISIBLE);
                        tvHomeTitle.setText("工作");
                        ByeBurgerBehavior.from(bottomHomeBar).show();
                        break;
                    case R.id.action_news:
                        tvHomeTitle.setText("资讯");
                        toolHomeBar.setVisibility(View.VISIBLE);
                        ByeBurgerBehavior.from(bottomHomeBar).show();
                        break;
                    case R.id.action_contacts:
                        tvHomeTitle.setText("我");
                        ByeBurgerBehavior.from(bottomHomeBar).show();
                        //隐藏toolbar
                        toolHomeBar.setVisibility(View.GONE);
                        break;
                }
                return true;
            }
        });
    }

    /***
     * 加载菜单
     */
    private void initleftmenu()
    {
        //headerview = leftMenu.getHeaderView(0);
        tv_left_avator = headerview.findViewById(R.id.tv_left_user_name_one);
        tv_left_name = headerview.findViewById(R.id.tv_left_user_name);
        tv_left_name.setText(CacheUtils.getInstance().getUser().getData().getName());
        tv_left_avator.setText(CacheUtils.getInstance().getUser().getData().getName().substring(0,1));
    }

    private void initui() {
        //关闭底部动画
        bottomHomeBar.enableItemShiftingMode(false);
        bottomHomeBar.enableAnimation(false);
        bottomHomeBar.enableShiftingMode(false);
        //获取角标的位置
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomHomeBar.getChildAt(0);
        BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(3);
        bage_view = LayoutInflater.from(this).inflate(R.layout.bage_view,menuView,false);
        itemView.addView(bage_view);
        img_notice_bage_view = bage_view.findViewById(R.id.tv_msg_count);
        //为navgationbar设置
        //        StatusBarUtil.setColorForDrawerLayout(this, draHomeLayout, Color.BLACK, 125);
        //设置viwepagaer
        viewPagerAdapter = new HomeViewPagerAdapter(getSupportFragmentManager(), fragments);
        viewHomePager.setAdapter(viewPagerAdapter);
        viewHomePager.setCurrentItem(0);
        viewHomePager.setOffscreenPageLimit(viewPagerAdapter.getCount());
        bottomHomeBar.setupWithViewPager(viewHomePager);
    }

    @Override
    protected void initdata() {
        //获取user
        user = CacheUtils.getInstance().getUser();
        //tvUserName.setText(CacheUtils.getInstance().getUser().getData().getName().substring(0,1));
        MyApplication.getClient().findAllMessage2(user.getData().getId());
        //初始化fragment
        initfragment();
    }

    /**
     * 初始化fragment
     */
    private void initfragment() {
        messageFragment = new MessageFragment();
        workFragment = new WorkFragment();
        meetingFragment = new MeetingFragment();
        newsFragment = new NewsFragment();
        constactFragment = new ConstactFragment();
        fragments.add(messageFragment);
        fragments.add(workFragment);
        fragments.add(newsFragment);
        fragments.add(constactFragment);
    }

    /**
     * DrawerLayout侧滑菜单开关
     */
    public void toggleDrawer() {
        if (draHomeLayout.isDrawerOpen(GravityCompat.START)) {
            draHomeLayout.closeDrawer(GravityCompat.START);
        } else {
            draHomeLayout.openDrawer(GravityCompat.START);
        }
    }

    /**
     * 监听back键处理
     * 1.关闭侧滑菜单
     * 2.返回键回home而不是退出
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            //返回为home键
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
        }
        return true;
    }

    @Override
    protected int setlayout() {
        return R.layout.activity_home;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void findAllMessage(FindAllMessage2Event eva)
    {
        if (eva.isOk())
        {
            messageBeanList.clear();
            //获取成功
            messageBeanList = eva.getBean().getData();
            parseData();

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MyApplication.getClient().findAllMessage2(user.getData().getId());
    }

    /**
     * 计算未读消息数量
     */
    private void parseData() {
        int count = 0;
        for (MessageBean bean:messageBeanList)
        {
            if (bean.getIsread()==0)
            {
                //递增
                count=count+1;
            }
        }
        if (count>0)
        {
            img_notice_bage_view.setVisibility(View.VISIBLE);
            BadgeDrawable drawable = new BadgeDrawable.Builder()
                    .number(count)
                    .type(BadgeDrawable.TYPE_NUMBER)
                    .textSize(17.5f)
                    .textColor(UiUtlis.getColor(R.color.colorAppTheme))
                    .badgeColor(UiUtlis.getColor(R.color.TopicItemNodeTextColor))
                    .build();
            img_notice_bage_view.setBackgroundDrawable(drawable);
            //设置fragment里更改数据
            constactFragment.updateCount(count);
        }
        else
        {
            img_notice_bage_view.setVisibility(View.GONE);
            //设置数据
            constactFragment.updateCount(0);
        }

    }

    /**
     * 更新角标(推送下来的)
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void recivepush(PushNotifyEvent event) {
        MyApplication.getClient().findAllMessage2(user.getData().getId());
    }
}
